%% Author: Dmitriid
%% Created: 20.09.2006
%% Description: TODO: Add desciption to orcas_soap_encoder
-module(orcas_soap_encoder).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([encode/1]).

%%
%% API Functions
%%

encode(X) when is_tuple(X) ->
    encode_tuple(X);    
encode([H|L]) ->
    encode(H) ++ encode(L);
encode([]) ->
    [];
encode(X) ->
    lists:flatten([X]).
%%
%% Local Functions
%%

encode_term(Term) when is_atom(Term)->
    lists:flatten(io_lib:format("~p",[Term]));
encode_term(Term) ->
    Term.

encode_tuple({Name, {attributes, Attributes}, SubTags}) ->
	"<" ++ encode_term(Name) ++ " " ++ attributes(Attributes) ++ ">" ++
            encode(SubTags) ++
    "</" ++ encode_term(Name) ++ ">";
encode_tuple(Tuple) ->
    encode_tuple(Tuple, 1, size(Tuple)).

encode_tuple(Tuple, 1, Size) ->
    "<" ++ encode_term(element(1, Tuple)) ++ ">" ++
            encode_tuple(Tuple, 2, Size) ++
    "</" ++ encode_term(element(1, Tuple)) ++ ">";
encode_tuple(Tuple, ElemNo, Size) when ElemNo =< Size ->
    encode(element(ElemNo, Tuple)) ++ encode_tuple(Tuple, ElemNo + 1, Size);
encode_tuple(_, _, _) ->
    [].

attributes([{Name, Value}|L]) ->
    Name ++ "=\"" ++ Value ++ "\" " ++ attributes(L);
attributes([]) ->
    [].